from flask_restful import Resource

from model.crud import QueryMultipleInstances
from model.tables import Comment, User
from restful.data import DataPid
from restful.response import ResponseSuccess
from restful.session import login_required, data


class PostComment(Resource):
    @data(DataPid())
    def get(self, data):
        comments = QueryMultipleInstances(Comment, {'pid': data['pid']})

        # 获取所有相关的用户ID
        user_ids = [comment.uid for comment in comments]

        # 批量查询这些用户
        users = User.query.filter(User.id.in_(user_ids)).all()
        user_map = {user.id: user.username for user in users}

        return ResponseSuccess(data=[{
            'cid': i.id,
            'uid': i.uid,
            'username': user_map.get(i.uid, '未知用户'),  # 添加username字段
            'time': i.time,
            'content': i.content
        } for i in comments])
